package cellmachine;

import javax.swing.JFrame;

import cell.Cell;
import field.Field;
import field.View;

public class CellMachine {

	public static void main(String[] args) {
		System.out.println("CellMachine is initializing...");

		// 定义网格大小
		Field field = new Field(30,30);
		System.out.println("CellMachine creates Field.");

		// 初始化网格
		// 遍历网格，生成细胞
		for ( int row = 0; row < field.getHeight(); row++ ) {
			for ( int col = 0; col < field.getWidth(); col++ ) {
				field.place(row, col, new Cell());
			}
		}
		System.out.println("CellMachine creates Cell and put them in Field.");
		// 遍历网格，初始化1/5的活细胞
		for ( int row = 0; row < field.getHeight(); row++ ) {
			for ( int col = 0; col < field.getWidth(); col++ ) {
				Cell cell = field.get(row, col);
				if ( Math.random() < 0.2 ) {
					cell.reborn();
				}
			}
		}
		System.out.println("CellMachine calls Cell to reborn.");

		View view = new View(field);
		System.out.println("CellMachine creates View using Field.");

		// GUI界面
		JFrame frame = new JFrame();	// JFrame是Java图形窗口
		// 点击按钮关闭窗口
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// 不可以改变大小
		frame.setResizable(false);
		frame.setTitle("Cells");
		frame.add(view);
		frame.pack();
		// 生成窗口
		frame.setVisible(true);

		System.out.println("CellMachine caretes JFrame using View.");

		//
		for ( int i=0; i<50; i++ ) {
			// 遍历网格，更新细胞的生死
			for ( int row = 0; row<field.getHeight(); row++ ) {
				for ( int col = 0; col<field.getWidth(); col++ ) {
					Cell cell = field.get(row, col);

					// 得到坐标周围的活细胞
					Cell[] neighbour = field.getNeighbour(row, col);

					// 统计活细胞的数量
					int numOfLive = 0;
					for ( Cell c : neighbour ) {
						if ( c.isAlive() ) {
							numOfLive++;
						}
					}
//					System.out.print("["+row+"]["+col+"]:");
//					System.out.print(cell.isAlive()?"live":"dead");
//					System.out.print(":"+numOfLive+"-->");

					// 如果细胞是活的，根据neighbour的情况，设定是否死亡
					if ( cell.isAlive() ) {
						if ( numOfLive <2 || numOfLive >3 ) {
							cell.die();
//							System.out.print("die");
						}
					} else if ( numOfLive == 3 ) {
						// 如果细胞是死的，也要根据neighbour的情况，设定是否复活
						cell.reborn();
//						System.out.print("reborn");
					}
//					System.out.println();
				}
			}
			System.out.println("CellMachine update Cell.");
			// 重新绘制界面
			frame.repaint();

			try {
				Thread.sleep(400);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}
